package win.larryzeal.jmx;

/**
 * Hello world!
 */

import com.sun.jdmk.comm.HtmlAdaptorServer;
import org.apache.commons.modeler.ManagedBean;
import org.apache.commons.modeler.Registry;
import win.larryzeal.jmx.mbean.modeler.Greet;

import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.modelmbean.ModelMBean;
import java.io.InputStream;

/**
 * agent level: MBeanServer
 */
public class GreetAgent {
	public static void main(String[] args) throws Exception{
// 需要将xml信息读入到Registry对象中；注意这里的Registry是指org.apache.commons.modeler.Registry
		Registry registry = Registry.getRegistry(null, null);
		InputStream stream = GreetAgent.class.getResourceAsStream("/mbeans-descriptors.xml"); //注意，如果不用/，那默认就是class类所在的位置
		registry.loadMetadata(stream);
		MBeanServer server = registry.getMBeanServer();

// 之前是：MBeanServer server = ManagementFactory.getPlatformMBeanServer();
		ManagedBean managed = registry.findManagedBean("Greet");
		ObjectName greetName = new ObjectName(managed.getDomain() + ":name=Greet");
// Greet greet = new Greet(); 为什么要多个createMBean？因为现在的写法没有写MBean,所以才要【动态】生成一个，以前就直接
// 把new Greet()注册到MBeanServer就可以了，server会自动找到它的HelloMBean接口文件。
		ModelMBean greet = managed.createMBean(new Greet());
		server.registerMBean(greet, greetName);

		ObjectName adapterName = new ObjectName(managed.getDomain() + ":name = htmladapter,port=8082");
		HtmlAdaptorServer adapter = new HtmlAdaptorServer();
		server.registerMBean(adapter, adapterName);
		adapter.start();
	}
}
